//
//  RegisterDetailInfo_Vc.swift
//  MikerShop
//
//  Created by eme on 2016/11/23.
//  Copyright © 2016年 eme. All rights reserved.
//

/*
 owner:cy
 update:2016年11月23日17:47:16
 info: 提交入驻资料
 */
import RxSwift
import CommonCore
import UtilCore
import ModelProtocol
import RickonCore
import BrandonCore

class RegisterDetailInfo_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var qymc_Border_V: UIView!
    
    @IBOutlet weak var qymc_Tf: UITextField!
    
    @IBOutlet weak var lxr_Border_V: UIView!
    
    @IBOutlet weak var lxr_Tf: UITextField!
    
    
    @IBOutlet weak var city_Border_V: UIView!
    
    ///审核状态显示
    @IBOutlet weak var sh_State_V: UIView!
    @IBOutlet weak var sh_state_V_Height_Lc: NSLayoutConstraint!
    @IBOutlet weak var sh_State_Lb: UILabel!
    
    @IBOutlet weak var address_Btn: UIButton!
    @IBOutlet weak var yyzzbh_Border_V: UIView!
    @IBOutlet weak var yyzzbh_Tf: UITextField!
    
    @IBOutlet weak var submit_Btn: UIButton!
    @IBOutlet weak var uploadPic_Btn: UIButton!
    /*----------------------------   自定义属性区域    ----------------------------*/
    let addressView = PickerAddressView()
    var glshop:GlShopModel?
    var manageVm :RegisterDetailInfo_Vm?
    var qiniuVm:Qiniu_Vm?
    var spid:String?
    ///表示是在注册的时候直接进来的，关闭的时候需要dismiss了，否则是我的或者首页配置进来的，关闭只需要pop即可
    var isFirst:Bool = false
    
    let updateViewSubject = PublishSubject<Void>()
    
     var reviewDetailsPageVm:ReviewDetailsPage_Vm?
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        self.submit_Btn.changeBorderColor(UIColor.clear, cornerRadius: 3.5)
        self.submit_Btn.backgroundColor = UIColor.clear
        self.submit_Btn.changeBackgroundImage(Theme.btn.normal, highlightedColor: Theme.btn.highlighted, disabledColor: Theme.btn.disabled)
        self.qymc_Border_V.changeBorderColor(Theme.tf.border, cornerRadius: 2.0,borderWidth:0.5 )
        self.lxr_Border_V.changeBorderColor(Theme.tf.border, cornerRadius: 2.0,borderWidth:0.5 )
        self.city_Border_V.changeBorderColor(Theme.tf.border, cornerRadius: 2.0,borderWidth:0.5 )
        self.yyzzbh_Border_V.changeBorderColor(Theme.tf.border, cornerRadius: 2.0,borderWidth:0.5 )
        self.qymc_Tf.changePlaceholder("请输入企业名称",placeColor:Theme.tf.placeorder,textColor:Theme.tf.text)
        self.lxr_Tf.changePlaceholder("请输入联系人姓名",placeColor:Theme.tf.placeorder,textColor:Theme.tf.text)
        self.yyzzbh_Tf.changePlaceholder("请输入营业执照编号",placeColor:Theme.tf.placeorder,textColor:Theme.tf.text)
        self.address_Btn.setTitle("请选择所在省市区", for: .normal)
        /// 设置button的title左对齐
        self.address_Btn.contentHorizontalAlignment = .left
        self.address_Btn.setTitleColor(Theme.tf.border, for: .normal)
        self.address_Btn.setTitleColor(Theme.tf.border, for: .selected)
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        AreaTool.sharedInstance.successAreaList.subscribe(onNext:{[unowned self] item in
            self.addressView.areaList = item
        }).addDisposableTo(disposeBag)
        
        AreaTool.sharedInstance.getVersionAreaList()
        self.address_Btn.rx.tap.subscribe(onNext: { [unowned self] ( _ ) in
            self.view.endEditing(true)
            self.addressView.show()
        }).disposed(by: disposeBag)
        self.addressView.logisticsRequest.subscribe(onNext:{ item in
            self.address_Btn.isSelected = true
            self.address_Btn.setTitle("\(item.province.areaname + item.city.areaname + item.area.areaname)", for: .normal)
            /// 省名称
            self.glshop?.agprovincename = item.province.areaname
            self.glshop?.agprovincecode = item.province.areacode
            //所在城市名称
            self.glshop?.spareaname = item.city.areaname
            self.glshop?.spareacode = item.city.areacode
            //所区域代码
            self.glshop?.agareaname = item.area.areaname
            self.glshop?.agareacode = item.area.areacode
            self.manageVm?.addressVariable.value = true
        }).addDisposableTo(disposeBag)
        self.uploadPic_Btn.rx.tap.subscribe(onNext: { [unowned self] ( _ ) in
            self.selectIcon()
        }).disposed(by: disposeBag)
        self.qiniuVm = Qiniu_Vm()
        self.qiniuVm?.uploadImageSuccess.subscribe(onNext: {[unowned self] (splicenseurl) in
            self.glshop?.splicenseurl = splicenseurl
            if let glshop = self.glshop{
                self.manageVm?.splicenseurlVariable.value = true
                self.uploadPic_Btn.setUrlImage(url: glshop.splicenseurl, forState: .normal)
            }
        }).addDisposableTo(disposeBag)

        self.manageVm = RegisterDetailInfo_Vm(input: (
            qymc: Observable.of(self.updateViewSubject.map{ self.qymc_Tf.text ?? ""}, qymc_Tf.rx.text.orEmpty.asObservable()).merge(),
            lxr: Observable.of(self.updateViewSubject.map{ self.lxr_Tf.text ?? ""}, lxr_Tf.rx.text.orEmpty.asObservable()).merge(),
            yyzzbh:Observable.of(self.updateViewSubject.map{ self.yyzzbh_Tf.text ?? ""}, yyzzbh_Tf.rx.text.orEmpty.asObservable()).merge() ,
            submitTaps: submit_Btn.rx.tap.map{_ in self.glshop!}
            ), validationService: RegisterImplementations())
        self.manageVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        self.manageVm?.signupEnabled
            .subscribe(onNext: {[unowned self] (valid) in
                self.submit_Btn.isEnabled = valid
            })
            .addDisposableTo(disposeBag)
        self.manageVm?.submitSuccess
            .subscribe(onNext: {[unowned self] (rel) in
                self.view.toastCompletion("恭喜，您的资料提交成功!请等待审核..."){ _ in
                    ///  这块需要返回上一页
                    if self.isFirst{
                        self.navigationController?.dismiss(animated: true, completion: nil)
                    }else{
                         self.navigationController?.popViewController(animated: true)
                    }
                    
                }
            })
            .addDisposableTo(disposeBag)
        self.manageVm?.signingIn.bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        
        self.manageVm?.getshopSuccess
            .subscribe(onNext: { [unowned self] (model) in
                self.updateCustomView(glShop: model)
            })
            .addDisposableTo(disposeBag)
        
        if isFirst {
            self.sh_State_V.isHidden = true
            self.sh_state_V_Height_Lc.constant = 0.0
            self.title = "提交认证资料"
        }else{
            self.sh_State_V.isHidden = false
            self.sh_state_V_Height_Lc.constant = 30.0
            self.title = "认证信息"
        }
        if let spid  = self.spid {
            self.manageVm?.getshopSubject.onNext(spid)
        }
    }
    
    /// 更新界面显示
    func updateCustomView(glShop:GlShopModel)  {
        self.glshop = glShop
        self.qymc_Tf.text = glShop.spcompany
        self.lxr_Tf.text = glShop.spcontact
        if glShop.agprovincename.characters.count > 0 || glShop.spareaname.characters.count > 0 || glShop.agareaname.characters.count > 0  {
            self.address_Btn.setTitle("\(glShop.agprovincename + glShop.spareaname + glShop.agareaname)", for: .normal)
        }
        if glShop.splicense.characters.count > 0 {
            self.yyzzbh_Tf.text = glShop.splicense
        }
        if glShop.splicenseurl.characters.count > 0 {
            self.uploadPic_Btn.setUrlImage(url: glShop.splicenseurl)
        }
        /// 修改状态 使按钮可以点击
        self.address_Btn.isSelected = true
        self.manageVm?.addressVariable.value = true
        self.manageVm?.splicenseurlVariable.value = true
        self.updateViewSubject.onNext()
    }
}

extension RegisterDetailInfo_Vc{
    ///改变头像
    func selectIcon()
    {
        let userIconAlert = UIAlertController(title: "请选择操作", message: "", preferredStyle: UIAlertControllerStyle.actionSheet)
        
        let chooseFromPhotoAlbum = UIAlertAction.init(title: "从相册选择", style: UIAlertActionStyle.default, handler: { UIAlertAction in
            self.ChooseFromPhotoAlbum()
        })
        
        let chooseFromCamera = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default,handler:{ UIAlertAction in
            self.ChooseFromCamera()
        })
        let canelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler: nil)
        userIconAlert.addAction(canelAction)
        userIconAlert.addAction(chooseFromCamera)
        userIconAlert.addAction(chooseFromPhotoAlbum)
        
        self.present(userIconAlert, animated: true, completion: nil)
        
    }
    //MARK:-
    //MARK:从相册选取图片
    func ChooseFromPhotoAlbum() -> Void{
        let imagePicker = UIImagePickerController()
        //设置代理
        imagePicker.delegate = self
        //允许编辑
        imagePicker.allowsEditing = true
        //设置图片源
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        //模态弹出IamgePickerView
        self.present(imagePicker, animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController)
    {
        picker.dismiss(animated: true, completion: nil)
    }
    
    //MARK:-
    //MARK:拍照
    func ChooseFromCamera() -> Void{
        let imagePicker = UIImagePickerController()
        //设置代理
        imagePicker.delegate = self
        //允许编辑
        imagePicker.allowsEditing=true
        //设置图片源
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        //模态弹出IamgePickerView
        self.present(imagePicker, animated: true, completion: nil)
    }
}

extension RegisterDetailInfo_Vc:UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    //MARK:imagePicker代理方法
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获得编辑后的图片
        if let image = (info as NSDictionary).object(forKey: UIImagePickerControllerEditedImage) as? UIImage  {
            self.qiniuVm?.uploadImageSubject.onNext(image)
        }
        picker.dismiss(animated: true, completion: nil)
    }
}
